<?php
/**
 * Created by PhpStorm.
 * User: *!N.J
 * Date: 2021/8/22
 * Time: 4:26
 * QQ:1467572213
 */

namespace app\en\controller;

use think\facade\Request;
use think\facade\Session;
use \app\index\model\Withdrawal as Withdrawal_m;
use think\Db;

class Withdrawal extends Base
{
    public function index()
    {
        $user_id = Session::get('user_id');
        $user_info = \app\index\model\Base::get_user_info($user_id);

        $service_tx = \app\index\model\Base::get_config($name = 'service_tx');
        $this->assign('service_tx',$service_tx);

        $min_money = \app\index\model\Base::get_config($name = 'min_money');
        $this->assign('min_money',$min_money);

        if (!$user_info['bank_name'] || !$user_info['holder_name'] || !$user_info['account_number'] || !$user_info['phone_number']){
            $is_card = 0;
        }else{
            $is_card = 1;
        }
        $this->assign('is_card',$is_card);
        return $this->fetch();
    }

    public function confirm_withdrawal()
    {
        $user_id = Session::get('user_id');
        $user_info = \app\index\model\Base::get_user_info($user_id);
        $start_withdrawal = \app\index\model\Base::get_config($name = 'start_withdrawal');
        $service_charge = \app\index\model\Base::get_config($name = 'service_tx');
        $min_money = \app\index\model\Base::get_config($name = 'min_money');
        
        if (Request::isPost()){
            $money = Request::post('money');
            $pass = Request::post('pass');
            $bank_code = Request::post('bank_code');
            // $type = Request::post('type');
            
            // $confirm_info['order_id'] = time().mt_rand(11111,99999);
            // $confirm_info['uid'] = $user_info['id'];
            // $confirm_info['pid'] = $user_info['pid'];
            // $confirm_info['username'] = $user_info['username'];
            // $confirm_info['phone'] = $user_info['phone'];
            // $confirm_info['apply_money'] = $money;
            // $confirm_info['service_money'] = $money * $service_charge / 100;
            // if ($confirm_info['service_money'] < $min_money){
            //     $confirm_info['service_money'] = $min_money;
            // }
            // $confirm_info['actual_money'] = $money - $confirm_info['service_money'];
            // $confirm_info['bank_name'] = $user_info['bank_name'];
            // $confirm_info['holder_name'] = $user_info['holder_name'];
            // $confirm_info['account_number'] = $user_info['account_number'];
            // $confirm_info['phone_number'] = $user_info['phone_number'];
            // $confirm_info['email'] = $user_info['email'];
            // $confirm_info['ifsc'] = $user_info['ifsc'];
            // $confirm_info['upi'] = $user_info['upi'];
            // $confirm_info['agent_check'] = 0;
            // $confirm_info['type'] = 2;
            // $confirm_info['status'] = 0;
            // $confirm_info['create_time'] = time();
            // $add_info = Db::name('fd_withdrawal')->insert($confirm_info);
            
            // $dec_money = Db::name('fd_user')->where('id',$user_id)->setDec($field,$money);
            
            // if($type == 1){
            //     $res = $this->flb_pay($money,$user_info,$confirm_info['order_id']);
                
            //     if($res['respCode'] == 'SUCCESS'){
            //         return ['code'=>1,'msg'=>'Success'];
            //     }else{
            //         return ['code'=>0,'msg'=>'Error'];
            //     }
            // }
            
            // if($type == 2){
            //     $res = $this->qeapay_pay($money,$user_info,$confirm_info['order_id']);
            //     // var_dump($res);die;
            //     if($res['respCode'] == 'SUCCESS'){
            //         return ['code'=>1,'msg'=>'Success'];
            //     }else{
            //         return ['code'=>0,'msg'=>'Error'];
            //     }
            // }
            
            
            
            
            $check_pass = Withdrawal_m::check_pass($user_id,$pass);
            if ($check_pass == 'error') return ['code'=>0,'msg'=>'Transaction password error'];
            $check_order = Withdrawal_m::check_order($user_id);
            if ($check_order == 'error') return ['code'=>0,'msg'=>'The task has not been completed. Please submit the application after completing the task'];
            $check_group_order_num = Withdrawal_m::check_group_order_num($user_info);
            if ($check_group_order_num == 'error') return ['code'=>0,'msg'=>'There are still unfinished orders in the group'];
            if (!$user_info['bank_name'] || !$user_info['holder_name'] || !$user_info['account_number'] || !$user_info['phone_number'] || !$user_info['ifsc']) return ['code'=>0,'msg'=>'Please bind your bank card before you make a withdrawal'];

            if ($money < $start_withdrawal) return ['code'=>0,'msg'=>'Less than the starting amount'];
            if ($money > $user_info['balance']) return ['code'=>0,'msg'=>'Your balance is insufficient'];
            $confirm = Withdrawal_m::confirm_withdrawal($user_info,$money,$service_charge,$min_money,$bank_code);
            switch ($confirm)
            {
                case 'success':
                    return ['code'=>1,'msg'=>'Success'];
                    break;
                case 'error':
                    return ['code'=>0,'msg'=>'Error'];
                    break;
            }
        }
    }
    
    public function qeapay_pay($money,$user_info,$order_sn){
        header("content-Type: text/html; charset=UTF-8");
        
        $mch_id = "104005778";
        $merchant_key = "JKXNF4NBKJZTWJNKYOI6VG6MGB4CZXU9";
        // $mch_id = "102001002";
        // $merchant_key = "QMHYTGCP3CSHQROIMRI9FATYKQ1HPQ3Q";
        
        
        $url = "https://payment.qeapay.com/pay/transfer";
        
        $data = array(
            'apply_date' => date("Y-m-d H:i:s"),
            'bank_code' => 'gcash',
            'mch_id' => $mch_id,
            'mch_transferId' => $order_sn,
            'receive_account' => $user_info['account_number'],
            'receive_name' => $user_info['bank_name'],
            'transfer_amount' => $money,
            'back_url' => Request::domain().'/index/notify/tx_notify'
            
        );
        
        $signStr = $this->asc_sort($data);
        $data['sign_type'] = 'MD5';
        $sign = $this->sign($signStr,$merchant_key);
        $data['sign'] = $sign;
        $result = $this->http_post_res($url,$data);
        
        $result = json_decode($result,true);
        return $result;
        
    }
    
    
    public function flb_pay($money,$user_info,$order_sn){
        header("content-Type: text/html; charset=UTF-8");
        
        $mch_id = "777805222";
        $merchant_key = "XLCCJ3SXNNBIBPWEJP5BJDAQYL4APDJ9";
        
        $url = "https://interface.wowpayglobal.com/pay/transfer";
        
        $data = array(
            'apply_date' => date("Y-m-d H:i:s"),
            'bank_code' => 'gcash',
            'mch_id' => $mch_id,
            'mch_transferId' => $order_sn,
            'receive_account' => $user_info['account_number'],
            'receive_name' => $user_info['bank_name'],
            'transfer_amount' => $money
        );
        
        $signStr = $this->asc_sort($data);
        $data['sign_type'] = 'MD5';
        $sign = $this->sign($signStr,$merchant_key);
        $data['sign'] = $sign;
        $result = $this->http_post_res($url,$data);
        
        $result = json_decode($result,true);
        return $result;
        
    }
    
    function asc_sort($params = array())
    {
        if (!empty($params)) {
            $p = ksort($params);
            if ($p) {
                $str = '';
                foreach ($params as $k => $val) {
                    $str .= $k . '=' . $val . '&';
                }
                $strs = rtrim($str, '&');
                return $strs;
            }
        }
        return false;
    }
    public function sign($signSource,$key) {
        if (!empty($key)) {
             $signSource = $signSource."&key=".$key;
        }
        // echo $signSource;die;
        return md5($signSource);
    }
    public function http_post_res($url,$data)
    {
        $ch = curl_init();    
        curl_setopt($ch,CURLOPT_URL,$url); //支付请求地址
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));  
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    
        $response=curl_exec($ch);
        curl_close($ch);

        return $response;
    }
}